package com.example.demo.controller;

import cn.hutool.core.util.RandomUtil;
import com.example.demo.constant.QualityConstants;
import com.example.demo.service.ExeclDemoService;
import com.example.demo.util.WordGeneratorUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhangfc
 * @date 2022/1/17 10:47
 */
@Api(tags = "execl处理controller")
@RestController
@RequestMapping("/execl")
@Slf4j
public class ExeclDemoController {

    @Autowired
    private ApplicationEventPublisher publisher;

    @GetMapping("/test")
    public void exportExecl(HttpServletRequest request, HttpServletResponse response) {

        Map<String, Object> countMap = new HashMap<>();
        List<Map<String, Object>> countList = new ArrayList<>();
        Map<String, Object> reponseMap = new HashMap<>();
        List<Map<String, Object>> reponseList = new ArrayList<>();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", "NEW BORUAN NAPPA 19-1656TPG 朱红 单位：SF");


        List<Map<String, Object>> tableList = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("num", "111058-50");
        map1.put("name", "里心年份标皮");
        map1.put("chang", 5);
        map1.put("kuan", 10.6);
        map1.put("js", "1/5");
        map1.put("equation","=RC[-3]*RC[-2]*IF(COUNTIF(RC[-1],&quot;*/*&quot;)&gt;0,&quot;0 &quot;&amp;RC[-1],RC[-1])/10000*10.7639");
        map1.put("compony", "美迪洋皮革");
        tableList.add(map1);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("num", "111058-50");
        map2.put("name", "里心年份标皮");
        map2.put("chang", 5);
        map2.put("kuan", 10.6);
        map2.put("js", "1/5");
        map2.put("equation","=RC[-3]*RC[-2]*IF(COUNTIF(RC[-1],&quot;*/*&quot;)&gt;0,&quot;0 &quot;&amp;RC[-1],RC[-1])/10000*10.7639");
        map2.put("compony", "美迪洋皮革");
        tableList.add(map2);
        Map<String, Object> map3 = new HashMap<>();
        map3.put("num", "111058-50");
        map3.put("name", "里心年份标皮");
        map3.put("chang", 5);
        map3.put("kuan", 10.6);
        map3.put("js", "1/5");
        map3.put("equation","=RC[-3]*RC[-2]*IF(COUNTIF(RC[-1],&quot;*/*&quot;)&gt;0,&quot;0 &quot;&amp;RC[-1],RC[-1])/10000*10.7639");
        map3.put("compony", "美迪洋皮革");
        tableList.add(map3);
        paramMap.put("tableList", tableList);
        reponseList.add(paramMap);


        reponseMap.put("paramList", reponseList);
        reponseMap.put("name", "主要材料");
        countList.add(reponseMap);


        Map<String, Object> reponseMap1 = new HashMap<>();
        List<Map<String, Object>> reponseList1 = new ArrayList<>();

        Map<String, Object> paramMap1 = new HashMap<>();
        paramMap1.put("name", "NEW BORUAN NAPPA 19-1656TPG 朱红 单位：SF");


        List<Map<String, Object>> tableList1 = new ArrayList<>();
        Map<String, Object> map11 = new HashMap<>();
        map11.put("num", "111058-50____");
        map11.put("name", "辅里心年份标皮");
        map11.put("chang", 5);
        map11.put("kuan", 10.6);
        map11.put("js", "1/5");
        map11.put("equation","=RC[-3]*RC[-2]*IF(COUNTIF(RC[-1],&quot;*/*&quot;)&gt;0,&quot;0 &quot;&amp;RC[-1],RC[-1])/10000*10.7639");
        map11.put("compony", "美迪洋皮革");
        tableList1.add(map11);
        Map<String, Object> map21 = new HashMap<>();
        map21.put("num", "111058-50____-50");
        map21.put("name", "辅里心年份标皮");
        map21.put("chang", 5);
        map21.put("kuan", 10.6);
        map21.put("js", "1/5");
        map21.put("equation","=RC[-3]*RC[-2]*IF(COUNTIF(RC[-1],&quot;*/*&quot;)&gt;0,&quot;0 &quot;&amp;RC[-1],RC[-1])/10000*10.7639");
        map21.put("compony", "美迪洋皮革");
        tableList1.add(map21);
        Map<String, Object> map31 = new HashMap<>();
        map31.put("num", "111058-111058-50____");
        map31.put("name", "辅里心年份标皮");
        map31.put("chang", 5);
        map31.put("kuan", 10.6);
        map31.put("js", "1/5");
        map31.put("equation","=RC[-3]*RC[-2]*IF(COUNTIF(RC[-1],&quot;*/*&quot;)&gt;0,&quot;0 &quot;&amp;RC[-1],RC[-1])/10000*10.7639");
        map31.put("compony", "美迪洋皮革");
        tableList1.add(map31);
        paramMap1.put("tableList", tableList1);
        reponseList1.add(paramMap1);


        reponseMap1.put("paramList", reponseList1);
        reponseMap1.put("name", "辅助材料");
        countList.add(reponseMap1);

        countMap.put("countList", countList);
        countMap.put("auther", "zhangfc");
        countMap.put("today", new Date());
        File file = WordGeneratorUtil.createDoc(WordGeneratorUtil.FreemarkerTempate.Test, WordGeneratorUtil.FreemarkerTempate.Test, countMap);

        InputStream ins = null;
        OutputStream out = null;


        try {
            ins = new FileInputStream(file);

            response.setCharacterEncoding("utf-8");

            response.setContentType("application/ms-excel");
            response.setContentType("application/x-msdownload");
            String filenameEncoder = "";
            // 其它浏览器
            filenameEncoder = URLEncoder.encode(WordGeneratorUtil.FreemarkerTempate.test_execl, "utf-8");
            response.setHeader(QualityConstants.ACCESS_CONTROL_ALLOW_ORIGIN, "*");//所有域都可以跨
            response.setHeader(QualityConstants.CONTENT_TYPE, QualityConstants.CONTENT_TYPE_STEAM);//二进制  流文件
            response.setHeader(QualityConstants.CONTENT_DISPOSITION, "attachment;filename=" + filenameEncoder + ".xls");//下载及其文件名
            response.setHeader(QualityConstants.CONNECTION, QualityConstants.CLOSE);//关闭请求头连接
            //设置文件在浏览器打开还是下载
            response.setContentType(QualityConstants.CONTENT_TYPE_DOWNLOAD);

            out = response.getOutputStream();


            byte[] buffer = new byte[QualityConstants.BYTE_512];

            int bytesToRead = QualityConstants.NUM_MINUS_1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while ((bytesToRead = ins.read(buffer)) != QualityConstants.NUM_MINUS_1) {
                out.write(buffer, QualityConstants.NUM_ZERO, bytesToRead);
            }

        } catch (Exception e) {

            e.printStackTrace();
        } finally {
            try {
                if (ins != null) {
                    ins.close();
                }
                if (out != null) {
                    out.close();
                }
                file.delete();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    /**
     * 测试文件下载形式
     *
     * @param request  请求
     * @param response 响应
     */
    @GetMapping("/test2")
    @ApiOperation("测试文件下载方式")
    public void fileTest(HttpServletRequest request, HttpServletResponse response) {
        File file = new File("D:\\1.jpg");
        FileInputStream ins = null;
        BufferedInputStream bis = null;
        ServletOutputStream ous = null;
        try {
            ins = new FileInputStream(file);
            bis = new BufferedInputStream(ins);
            ous = response.getOutputStream();
            String fileName = RandomUtil.randomString(6);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8") + ".jpg");
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
                ous.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Autowired
    private ExeclDemoService execlDemoService;

    private static AtomicInteger atomicInteger = new AtomicInteger(0);

    /**
     * 异步执行方式测试
     */
    @GetMapping("/user")
    public void testUser() {
        log.info("主方法执行开始>>>>>>");
        int i = atomicInteger.incrementAndGet();
//        publisher.publishEvent(new NoticeEvent("命令事件执行"));
        System.out.println(i);
        execlDemoService.sout(i);
        log.info("主方法执行结束>>>>>>");
    }
}
